package org.siam.impl {
	
	import flash.utils.Dictionary;
	
	import org.siam.core.schemas.ISchema;
	import org.siam.core.schemas.properties.ISchemaProperty;
	import org.siam.impl.data.editors.EditorsManagerXMLHandler;
	import org.siam.impl.data.formatters.FormattersManagerXMLHandler;
	import org.siam.impl.data.renderers.RenderersManagerXMLHandler;
	import org.siam.impl.data.validators.ValidatorsManagerXMLHandler;
	import org.siam.impl.schemas.SchemaXMLHandler;
	import org.siam.utils.RuntimeError;
	import org.siam.utils.StringUtils;
	
	public class SiamManagerXMLHandler {
		
		public static function read(input:XML, instance:SiamManager):void {
			if (input == null) 
				throw new RuntimeError("XML Configuration is missing!")
			
			if (input.name() != "siam-configuration") 
				throw new RuntimeError("The configuration must be started with the tag <siam-configuration>");
			
			// Parsing Formatting section
			var formatting:XMLList = input.child("formatters");
			instance._formatters = FormattersManagerXMLHandler.read(formatting[0]);
			
			// Parsing Rendering section
			var rendering:XMLList = input.child("renderers");
			instance._renderers = RenderersManagerXMLHandler.read(rendering[0]);
			
			// Parsing Editing section
			var editing:XMLList = input.child("editors");
			instance._editors = EditorsManagerXMLHandler.read(editing[0]);
			
			// Parsing Validation section
			var validation:XMLList = input.child("validators");
			instance._validators = ValidatorsManagerXMLHandler.read(validation[0]);
			
			// Parsing each mapping
			var mappingXML:XMLList = input.child("schemas");
			instance._schemas = new Dictionary(); // Reset registry
		    parseSchemas(instance, mappingXML[0]);	
		}
		
		private static function parseSchemas(instance:SiamManager, input:XML):void {
			if (!input)
				return;

			// iterates thru schemas
			for each (var schemaXML:XML in input["schema"]) {
				var schema:ISchema = SchemaXMLHandler.read(schemaXML, instance);
				var schemaId:String = schema.id;
				if (!schemaId) {
					throw new RuntimeError("A schema must have a valid id");
				} else if (instance.hasSchema(schemaId)) {
					throw new RuntimeError("Duplicated schema id '{0}'", schemaId);
				}
				instance.registerSchema(schemaId, schema);
			}	
		}
	}
}